'use strict'
import {
  Model,
  DataTypes,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from 'sequelize'
import dayjs from 'dayjs'
import Attribute from './attribute'
import AttributeAttributeValue from './attributeattributevalue'
import { Models } from '../type'
import sequelize from '.'

class AttributeValue extends Model<
  InferAttributes<AttributeValue>,
  InferCreationAttributes<AttributeValue>
> {
  declare id: CreationOptional<number>
  declare value: string
  declare createdAt: CreationOptional<Date>
  declare updatedAt: CreationOptional<Date>

  static associate(models: Models) {
    AttributeValue.belongsToMany(models.Attribute, {
      through: AttributeAttributeValue,
      foreignKey: 'attributeValueId',
      as: 'attributes',
    })
  }
}
AttributeValue.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    value: {
      type: DataTypes.STRING,
      allowNull: false,
      // unique: {
      //   name: 'value',
      //   msg: '属性值已存在。',
      // },
      validate: {
        notNull: {
          msg: '属性值必须填写。',
        },
        notEmpty: {
          msg: '属性值不能为空。',
        },
        len: {
          args: [2, 45],
          msg: '属性值长度必须在2~45个字符之间。',
        },
        isUnique: async (value: string) => {
          const val = await AttributeValue.findOne({ where: { value } })
          if (val) {
            throw new Error(`属性值【${value}】已存在。`)
          }
        },
      },
    },
    createdAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('createdAt')
          ? dayjs(this.getDataValue('createdAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
    updatedAt: {
      type: DataTypes.DATE,
      get() {
        return this.getDataValue('updatedAt')
          ? dayjs(this.getDataValue('updatedAt')).format('YYYY-MM-DD HH:mm:ss')
          : null
      },
    },
  },
  {
    sequelize,
    modelName: 'AttributeValue',
  },
)

export default AttributeValue
